import { loadArcGIS } from './BQGIS_ArcgisVector'

/**
 *
 * @param   viewer          cesium 或 mars3d实例
 * @param   children        数据列表（详情参考下方children元素）
 * @param   label           用于渲染tree控件时的标签显示(可选)
 * @param   id              用于渲染tree控件(可选)
 * @param   customLoad      加载函数(可选，如果传入则按照该函数解析矢量json)
 *
 * @function init           重置矢量数据，传入新的矢量列表，会根据新列表与旧列表的差异更新图层
 * @function show           指定图层显示/隐藏
 */

  /**
 *  children元素
 *  @param   id             唯一标识
 *  @param   url            矢量地址
 *  @param   show           矢量是否显示
 *  @param   label          用于渲染tree控件时的标签显示
 * 
 */
export function BQGIS_VectorManager ({children, label = "矢量", id = getUUId(), viewer, customLoad = null}) {
    this.viewer = viewer
    this.id = id
    this.label = label
    this.children = []
    this.customLoad = customLoad
    this.init(children)
}

BQGIS_VectorManager.prototype.init = function (children) {
    const keys = this.children.map(item => item.id)
    children.forEach(item => {
        const layerData = this.children.find(data => data.id === item.id)
        if(layerData){
            const index = keys.findIndex(id => id === item.id)
            keys.splice(index, 1)
            this.upDate(layerData, item)
        }else{
            this.add(item)
        }
    })
    keys.forEach(id => {
        this.remove(id)
    })
}

BQGIS_VectorManager.prototype.upDate = function (layerData, option) {
    if(option.url !== layerData.url){
        if(layerData.entity){
            this.viewer.dataSources.remove(layerData.entity)
        }
        layerData.entity = null
        layerData.url = option.url
    }
    this.setShow(layerData, option.show)
    layerData = Object.assign(layerData, option)
}



BQGIS_VectorManager.prototype.add = function (option) {
    const layerData = this.loadImageryLayer(option)
    this.children.push(layerData)
    return layerData
}

BQGIS_VectorManager.prototype.loadImageryLayer = function (option) {
    if(!option.id){
        option.id = getUUId()
    }
    this.setShow(option, option.show)
    return option
}

/**
 *
 * 3dtiles 显示隐藏
 * 
 * @param   id              
 * @param   show            显示/隐藏
 */
BQGIS_VectorManager.prototype.show = function ({id, show}) {
    const layerData = this.get(id)
    if(layerData){
        this.setShow(layerData, show)
    }
}

BQGIS_VectorManager.prototype.get = function (id) {
    return this.children.find(item => item.id === id)
}


BQGIS_VectorManager.prototype.flyTo = function (id) {
    const layerData = this.get(id)
    this.viewer.flyTo(layerData.entity)
}

BQGIS_VectorManager.prototype.setShow = function (layerData, show) {
    if(!layerData.entity && show){
            try{
                const dataSource = new Cesium.CustomDataSource(layerData.id);
                this.viewer.dataSources.add(dataSource);
                if(this.customLoad){
                    this.customLoad({entityCollection: dataSource, layerData})
                }else {
                    if (layerData.url.indexOf("arcgis") > -1) {
                        loadArcGIS({ entityCollection: dataSource, layerData})
                    }
                }
                layerData.entity = dataSource
            } catch (e) {
                console.error(e)
            }
    }
    if(layerData.entity){
        layerData.entity.show = show
    }
    layerData.show = show
}

BQGIS_VectorManager.prototype.remove = function (id) {
    const index = this.children.findIndex(item => item.id === id)
    const layerData = this.children[index]
    if(index !== -1){
        if(layerData.entity){
            this.viewer.dataSources.remove(layerData.entity)
            layerData.entity = null
        }
        this.children.splice(index, 1)
    }
}

/**
 * 获取当前所有显示的3dtiles的 id
 */
BQGIS_VectorManager.prototype.getShowKeys = function () {
    const data = []
    this.children.forEach(item => {
        if(item.show){
            data.push(item.id)
        }
    });
    return data
}

function getUUId() {
    let tem = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    let id = "",
        len = tem.length,
        i = 0
    for (i; i < len; i++) {
        if (tem[i] == "-") id += tem[i]
        else {
            let num = Math.floor(Math.random() * 16)
            id += num.toString(16)
        }
    }
    return id
}